import os
import Image
from spritemaker.rectangle import Rectangle
from spritemaker.sprite import SpriteItem
from spritemaker.sprite import SpriteBuilder

def Parse(codefile):
    builder = SpriteBuilder()

    basedir = os.path.dirname (codefile)
    
    
    def ImageFactory(filename, x, y, cssclass=None):
        
        img = Image.open (os.path.join (basedir, filename))
    
        itm = SpriteItem ()
        
        itm.filename = filename
        itm.image = img
        itm.bounds = Rectangle (x, y, x + itm.image.size[0], y + itm.image.size[1])

        if not cssclass:
            cssclass = os.path.basename (filename).replace(".", "_").replace (" ", "_")

        itm.cssclass = cssclass

        builder.AddSprite (itm)
        
    exec open(codefile) in { "Image" : ImageFactory }

    return builder
